<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { usePopWinInject, validFormRef, validFormThen } from '../../../../../common/hooks/FormHooks'
import { updateUserPasswordApi } from '../../../../../common/service/api/userApi'
import { sendServiceData } from '../../../../../common/service'
import { popMessage } from '../../../../../common/utils/normalUtils'

const emit = defineEmits(['loading'])
const state:any = reactive({
  isLoading: false,
  formData: {
    confirmPassword: '',
    oldPassword: '',
    newPassword: ''
  },
  rules: {
    oldPassword: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
    newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
    confirmPassword: [{ required: true, message: '确认密码不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (state.formData.newPassword && state.formData.confirmPassword &&
              state.formData.newPassword !== state.formData.confirmPassword) callback(new Error('两次密码输入不一致！'))
          else callback()
        },
        trigger: 'blur'
      }]
  }
})

// 表单组件引用
const formRef = ref()

const setLoading = (val:boolean) => {
  state.isLoading = val
  emit('loading', val)
}

const submitHandler = async () => {
  const send = {
    oldPassword: state.formData.oldPassword,
    newPassword: state.formData.newPassword
  }
   validFormThen(formRef, async () => {
     await sendServiceData(updateUserPasswordApi, send, setLoading)
     popMessage('修改成功！')
  })
}

</script>

<template>
  <el-form ref="formRef"
           :style="{width:'100%'}"
           :model="state.formData"
           :rules="state.rules"
           :label-width="100"
           class="z-normal-form-gl"
           status-icon>
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model.trim="state.formData.oldPassword" placeholder="请输入旧密码" type="password" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model.trim="state.formData.newPassword" placeholder="请输入新密码" type="password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model.trim="state.formData.confirmPassword" placeholder="请确认密码" type="password" />
    </el-form-item>
    <el-form-item label="">
      <div class="footer-ly">
        <el-button type="primary" @click="submitHandler">
          确 定
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
  .footer-ly{
    @include hor-group();
    width:100%;
    margin-top: 10px;
  }
</style>
